import React, {useEffect, useState} from 'react';
import {Edit2, Plus, Save, Trash2} from 'lucide-react';
import {Req} from '../../util/fetch';
import DeleteConfirmModal from '../../components/modals/DeleteConfirmModal';

export default function AdminSettings() {
    const [regions, setRegions] = useState<any[]>([]);
    const [teams, setTeams] = useState<any[]>([]);
    const [depts, setDepts] = useState<any[]>([]);
    const [activeTab, setActiveTab] = useState<'regions' | 'teams' | 'depts'>('regions');
    const [showModal, setShowModal] = useState(false);
    const [editingItem, setEditingItem] = useState<any>({});
    const [editState, setEditState] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [curId, setCurId] = useState<string>('');
    const [teamFilter, setTeamFilter] = useState<string>('');


    const handleAdd = () => {
        if (activeTab === 'regions') {
            setEditingItem({
                id: '',
                name: '',
                code: '',
                citys: '',
            });
        } else if (activeTab === 'teams') {
            setEditingItem({
                id: '',
                name: '',
                areaId: null,
                leaderName: ''
            });
        } else {
            setEditingItem({
                id: '',
                name: '',
                teamId: null,
            });
        }
        setEditState(false);
        setShowModal(true);
    };

    const handleEdit = (item: any) => {
        if (activeTab === 'regions') {
            setEditingItem({
                id: item.id,
                name: item.name,
                code: item.code,
                citys: item.citys,
            });
        } else if (activeTab === 'teams') {
            setEditingItem({
                id: item.id,
                name: item.name,
                areaId: item.areaId,
                leaderName: item.leaderName
            });
        } else {
            setEditingItem({
                id: item.id,
                name: item.name,
                teamId: item.teamId,
            });
        }
        setEditState(true);
        setShowModal(true);
    };

    const handleDelete = async (id: string) => {
        setShowDeleteModal(true);
        setCurId(id);
    };

    const submitForm = async (e) => {
        e.preventDefault()
        console.log(editingItem);
        const method = editState ? 'PUT' : 'POST';
        if (activeTab === 'regions') {
            const res = await Req(editState ? '/bsArea/edit' : '/bsArea/add', {method, body: editingItem})
            if (res.success) {
                setShowModal(false);
                queryAreaList()
            } else {
                alert(res.message)
            }
        } else if (activeTab === 'teams') {
            const res = await Req(editState ? '/bsTeam/edit' : '/bsTeam/add', {method, body: editingItem})
            if (res.success) {
                setShowModal(false);
                queryTeamList()
            } else {
                alert(res.message)
            }
        } else {
            const res = await Req(editState ? '/bsDepart/edit' : '/bsDepart/add', {method, body: editingItem})
            if (res.success) {
                setShowModal(false);
                queryDeptList()
            } else {
                alert(res.message)
            }
        }
    }

    const queryTeamList = async () => {
        const res = await Req('/bsTeam//list');
        if (res.success) {
            setTeams(res.data);
        } else {
            alert(res.message)
        }
    };

    const queryAreaList = async () => {
        const res = await Req('/bsArea/list');
        if (res.success) {
            setRegions(res.data);
        } else {
            alert(res.message)
        }
    };

    const queryDeptList = async () => {
        const res = await Req('/bsDepart/list');
        if (res.success) {
            setDepts(res.data);
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryTeamList()
        queryAreaList()
        queryDeptList()
    }, []);

    return (
        <div>
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-gray-900">系统设置</h1>
                <p className="text-gray-500">管理系统基础配置</p>
            </div>

            {/* 选项卡 */}
            <div className="flex space-x-4 mb-6">
                <button
                    onClick={() => setActiveTab('regions')}
                    className={`px-4 py-2 rounded-lg font-medium ${
                        activeTab === 'regions'
                            ? 'bg-blue-500 text-white'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                >
                    区域管理
                </button>
                <button
                    onClick={() => setActiveTab('teams')}
                    className={`px-4 py-2 rounded-lg font-medium ${
                        activeTab === 'teams'
                            ? 'bg-blue-500 text-white'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                >
                    团队管理
                </button>
                <button
                    onClick={() => setActiveTab('depts')}
                    className={`px-4 py-2 rounded-lg font-medium ${
                        activeTab === 'depts'
                            ? 'bg-blue-500 text-white'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                >
                    部门管理
                </button>
            </div>

            {/* 工具栏 */}
            <div className="flex justify-between items-center mb-6">
                <h2 className="text-lg font-semibold text-gray-900">
                    {activeTab === 'regions' ? '区域列表' : (activeTab === 'teams' ? '团队列表' : '部门列表')}
                </h2>
                {activeTab === 'depts' &&
                    <select
                        value={teamFilter}
                        onChange={(e) => setTeamFilter(e.target.value)}
                        style={{width: '350px'}}
                        className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                        <option value=''>全部团队</option>
                        {teams.map(region => (
                            <option key={region.id} value={region.id}>
                                {region.name}
                            </option>
                        ))}
                    </select>}
                <button
                    onClick={handleAdd}
                    className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                    <Plus className="w-5 h-5 mr-2"/>
                    {activeTab === 'regions' ? '添加区域' : (activeTab === 'teams' ? '添加团队' : '添加部门')}
                </button>
            </div>

            {/* 区域管理 */}
            {activeTab === 'regions' && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {regions.map(region => (
                        <div
                            key={region.id}
                            className="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all duration-300"
                        >
                            <div className="flex items-center justify-between mb-4">
                                <div className="flex items-center space-x-3">
                                    <span className="text-xl font-bold text-gray-900">{region.name}</span>
                                    <span className="px-2 py-1 bg-blue-100 text-blue-600 rounded text-sm">
                    {region.code}
                  </span>
                                </div>
                                <div className="flex space-x-2">
                                    <button
                                        onClick={() => handleEdit(region)}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                    >
                                        <Edit2 className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => handleDelete(region.id)}
                                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                </div>
                            </div>
                            <div className="flex flex-wrap gap-2">
                                {region.citys.split(',').map((city, index) => (
                                    <span
                                        key={index}
                                        className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm"
                                    >
                    {city}
                  </span>
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* 团队管理 */}
            {activeTab === 'teams' && (
                <div className="bg-white rounded-xl shadow-sm overflow-hidden">
                    <table className="w-full">
                        <thead>
                        <tr className="bg-gray-50 border-b">
                            <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">团队名称</th>
                            <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">所属区域</th>
                            <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">负责人</th>
                            <th className="px-6 py-4 text-center text-sm font-medium text-gray-500">成员数量</th>
                            <th className="px-6 py-4 text-right text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody className="divide-y">
                        {teams.map(team => (
                            <tr key={team.id} className="hover:bg-gray-50">
                                <td className="px-6 py-4">
                                    <span className="font-medium text-gray-900">{team.name}</span>
                                </td>
                                <td className="px-6 py-4 text-gray-500">{team.areaName}</td>
                                <td className="px-6 py-4 text-gray-500">{team.leaderName}</td>
                                <td className="px-6 py-4 text-center text-gray-500">{team.memberCount}</td>
                                <td className="px-6 py-4 ">
                                    <div className="flex items-center justify-end space-x-3">
                                        <button
                                            onClick={() => handleEdit(team)}
                                            className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        >
                                            <Edit2 className="w-5 h-5"/>
                                        </button>
                                        <button
                                            onClick={() => handleDelete(team.id)}
                                            className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                        >
                                            <Trash2 className="w-5 h-5"/>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* 部门管理 */}
            {activeTab === 'depts' && (
                <div className="bg-white rounded-xl shadow-sm overflow-hidden">
                    <table className="w-full">
                        <thead>
                        <tr className="bg-gray-50 border-b">
                            <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">部门名称</th>
                            <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">所属团队</th>
                            <th className="px-6 py-4 text-center text-sm font-medium text-gray-500">成员数量</th>
                            <th className="px-6 py-4 text-right text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody className="divide-y">
                        {depts.filter(dept => dept.teamId == teamFilter || teamFilter == '').map(dept => (
                            <tr key={dept.id} className="hover:bg-gray-50">
                                <td className="px-6 py-4">
                                    <span className="font-medium text-gray-900">{dept.name}</span>
                                </td>
                                <td className="px-6 py-4 text-gray-500">{dept.team?.name}</td>
                                <td className="px-6 py-4 text-center text-gray-500">{dept.memberCount}</td>
                                <td className="px-6 py-4 ">
                                    <div className="flex items-center justify-end space-x-3">
                                        <button
                                            onClick={() => handleEdit(dept)}
                                            className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        >
                                            <Edit2 className="w-5 h-5"/>
                                        </button>
                                        <button
                                            onClick={() => handleDelete(dept.id)}
                                            className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                        >
                                            <Trash2 className="w-5 h-5"/>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* 编辑/添加模态框 */}
            {showModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-xl p-6 w-full max-w-md">
                        <h2 className="text-xl font-semibold mb-4">
                            {editState ? '编辑' : '添加'}
                            {activeTab === 'regions' ? '区域' : (activeTab == 'teams' ? '团队' : '部门')}
                        </h2>
                        <form className="space-y-4">
                            {activeTab === 'regions' ? (
                                <>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            区域名称
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.name}
                                            onChange={(e) => editingItem.name = e.target.value}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            区域代码
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.code}
                                            onChange={(e) => editingItem.code = e.target.value}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            城市列表
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="请用逗号分隔城市名称"
                                            defaultValue={editingItem?.citys}
                                            onChange={(e) => editingItem.citys = e.target.value}
                                        />
                                    </div>
                                </>
                            ) : activeTab == 'teams' ? (
                                <>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            团队名称
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.name}
                                            onChange={(e) => editingItem.name = e.target.value}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            所属区域
                                        </label>
                                        <select
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.areaId}
                                            onChange={(e) => editingItem.areaId = e.target.value}
                                        >
                                            <option value=''>请选择</option>
                                            {regions.map(region => (
                                                <option key={region.id} value={region.id}>
                                                    {region.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            负责人
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.leaderName}
                                            onChange={(e) => editingItem.leaderName = e.target.value}
                                        />
                                    </div>
                                </>
                            ) : (
                                <>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            部门名称
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.name}
                                            onChange={(e) => editingItem.name = e.target.value}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">
                                            所属团队
                                        </label>
                                        <select
                                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            defaultValue={editingItem?.teamId}
                                            onChange={(e) => editingItem.teamId = e.target.value}
                                        >
                                            <option value=''>请选择</option>
                                            {teams.map(region => (
                                                <option key={region.id} value={region.id}>
                                                    {region.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                </>
                            )}
                            <div className="flex justify-end space-x-3 pt-4">
                                <button
                                    type="button"
                                    onClick={() => setShowModal(false)}
                                    className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
                                >
                                    取消
                                </button>
                                <button
                                    type="submit"
                                    onClick={submitForm}
                                    className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center"
                                >
                                    <Save className="w-5 h-5 mr-2"/>
                                    保存
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
            {showDeleteModal && (
                <DeleteConfirmModal
                    title="删除确认"
                    message={`确定要删除？`}
                    onConfirm={async () => {
                        if (activeTab === 'regions') {
                            await Req(`/bsArea/batch?ids=${curId}`, {method: 'DELETE'});
                            queryAreaList()
                        } else if (activeTab === 'teams') {
                            await Req(`/bsTeam/batch?ids=${curId}`, {method: 'DELETE'});
                            queryTeamList()
                        } else {
                            await Req(`/bsDepart/batch?ids=${curId}`, {method: 'DELETE'});
                            queryDeptList()
                        }
                        setShowDeleteModal(false)
                    }}
                    onCancel={() => {
                        setShowDeleteModal(false)
                    }}
                />
            )}
        </div>
    );
}